package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import com.beust.jcommander.internal.Lists;
import com.zhijian.medical.dao.local.MeetingDataNewMapper;
import com.zhijian.medical.entity.dto.FaceMeetingSyncMeetingRequestDto;
import com.zhijian.medical.entity.dto.FaceMeetingSyncMeetingResponseDto;
import com.zhijian.medical.entity.po.MeetingDataNew;
import com.zhijian.medical.entity.po.Person;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.request.MeetingRoomApplyVo;
import com.zhijian.medical.entity.vo.response.*;
import com.zhijian.medical.enums.*;
import com.zhijian.medical.exception.BusinessException;
import com.zhijian.medical.service.FileService;
import com.zhijian.medical.service.MeetingDataNewService;
import com.zhijian.medical.service.MeetingRoomService;
import com.zhijian.medical.service.PersonService;
import com.zhijian.medical.util.EncryptUtil;
import com.zhijian.medical.util.FaceMeetingUtil;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会议表格数据业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-06-05 14:50:36
 */
@Slf4j
@Service
public class MeetingDataNewServiceImpl implements MeetingDataNewService {

    @Autowired
    private MeetingDataNewMapper mapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private MeetingRoomService meetingRoomService;

    @Autowired
    private PersonService personService;

    @Override
    public MeetingDataNew selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public MeetingDataNewVo selectVoById(Long id) {
        MeetingDataNewVo meetingDataNewVo = mapper.selectVoById(id);
        if (Objects.isNull(meetingDataNewVo)) {
            return null;
        }
        //PPT文件地址数组
        List<FileVo> visitFileVos = fileService.selectList(FileSearchVo.builder()
                .dataId(meetingDataNewVo.getId())
                .type(FileTypeEnum.TEACH_PPT.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(visitFileVos)) {
            meetingDataNewVo.setPptFilePathList(visitFileVos.stream().map(fileVo -> {
                FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                fileSaveOrUpdateVo.setFileName(fileVo.getName());
                fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                return fileSaveOrUpdateVo;
            }).collect(Collectors.toList()));
        }
        //图片文件地址数组
        List<FileVo> picFileVos = fileService.selectList(FileSearchVo.builder()
                .dataId(meetingDataNewVo.getId())
                .type(FileTypeEnum.TEACH_PIC.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(picFileVos)) {
            meetingDataNewVo.setPicFilePathList(picFileVos.stream().map(fileVo -> {
                FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                fileSaveOrUpdateVo.setFileName(fileVo.getName());
                fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                return fileSaveOrUpdateVo;
            }).collect(Collectors.toList()));
        }
        return meetingDataNewVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }


    @Override
    public Long insert(MeetingDataNew meetingDataNew) {
        Date now = new Date();
        meetingDataNew.setCreateTime(now);
        meetingDataNew.setUpdateTime(now);
        return mapper.insert(meetingDataNew) > 0 ? meetingDataNew.getId() : 0L;
    }

    @Override
    public Long insertSelective(MeetingDataNew meetingDataNew) {
        Date now = new Date();
        meetingDataNew.setCreateTime(now);
        meetingDataNew.setUpdateTime(now);
        return mapper.insertSelective(meetingDataNew) > 0 ? meetingDataNew.getId() : 0L;
    }

    @Override
    public boolean update(MeetingDataNew meetingDataNew) {
        Date now = new Date();
        meetingDataNew.setUpdateTime(now);
        return mapper.updateByPrimaryKey(meetingDataNew) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(MeetingDataNew record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean save(MeetingDataNewSaveOrUpdateVo saveOrUpdateVo) {
        MeetingRoomVo meetingRoomDayVo = meetingRoomService.selectByName(saveOrUpdateVo.getAddress());
        //预约人姓名
        String userName = saveOrUpdateVo.getUserName();
        if (Objects.nonNull(meetingRoomDayVo)) {
            //会议室预约
            MeetingRoomApplyVo meetingRoomApplyVo = new MeetingRoomApplyVo();
            meetingRoomApplyVo.setDay(Integer.valueOf(saveOrUpdateVo.getDate().replaceAll("-", "")));
            meetingRoomApplyVo.setMeetingRoomId(meetingRoomDayVo.getId());

            MeetingRoomHourEnum meetingRoomHourEnum = MeetingRoomHourEnum.getByBeginTime(saveOrUpdateVo.getTime());
            AssertUtil.notNull(meetingRoomHourEnum, "时间只能是整点或者半点");
            List<Integer> hours = Lists.newLinkedList();
            //一小时
            assert meetingRoomHourEnum != null;
            hours.add(meetingRoomHourEnum.getCode());
            hours.add(meetingRoomHourEnum.getCode() + 1);
            meetingRoomApplyVo.setHour(hours);
            meetingRoomApplyVo.setUserId(saveOrUpdateVo.getUserId());
            meetingRoomApplyVo.setApplyUserPhone(saveOrUpdateVo.getUserPhone());
            meetingRoomApplyVo.setApplyUserName(userName);
            meetingRoomApplyVo.setMeetingType(saveOrUpdateVo.getType());
            if (StringUtils.isBlank(saveOrUpdateVo.getTitle())) {
                meetingRoomApplyVo.setMeetingName(saveOrUpdateVo.getDpPoint());
            } else {
                meetingRoomApplyVo.setMeetingName(saveOrUpdateVo.getTitle());
            }
            meetingRoomService.apply(meetingRoomApplyVo);
        }
        MeetingDataNew meetingDataNew = new MeetingDataNew();
        BeanUtils.copyProperties(saveOrUpdateVo, meetingDataNew);
        if (StringUtils.isBlank(saveOrUpdateVo.getTitle())) {
            meetingDataNew.setTitle(saveOrUpdateVo.getDpPoint());
        }

        FaceMeetingSyncMeetingRequestDto faceMeetingSyncMeetingRequestDto = new FaceMeetingSyncMeetingRequestDto();
        faceMeetingSyncMeetingRequestDto.setTheme(saveOrUpdateVo.getTitle());
        faceMeetingSyncMeetingRequestDto.setMrname(saveOrUpdateVo.getAddress());
        faceMeetingSyncMeetingRequestDto.setStime(saveOrUpdateVo.getDate() + " " + saveOrUpdateVo.getTime());
        DateTime startTimeDate = DateUtil.parseDateTime(saveOrUpdateVo.getDate() + " " + saveOrUpdateVo.getTime() + ":00");
        //默认一小时后结束
        DateTime endTimeDate = DateUtil.offsetHour(startTimeDate, 1);
        faceMeetingSyncMeetingRequestDto.setEtime(DateUtil.format(endTimeDate, new SimpleDateFormat("yyyy-MM-dd HH:mm")));
        faceMeetingSyncMeetingRequestDto.setUsername(userName);

        FaceMeetingSyncMeetingResponseDto faceMeetingSyncMeetingResponseDto = FaceMeetingUtil.setMeeting(faceMeetingSyncMeetingRequestDto);
        try {
            if (Objects.nonNull(faceMeetingSyncMeetingResponseDto)) {
                //保存远程会议ID
                meetingDataNew.setRemoteMeetingId(faceMeetingSyncMeetingResponseDto.getReturnData().getMeetingid());
            }
        } catch (Exception v) {
            v.printStackTrace();
        }
        //设置教学记录人签名和带教老师签名
        setJlrAndTeacherSign(saveOrUpdateVo, meetingDataNew);
        return this.insert(meetingDataNew) != 0;
    }

    /**
     * 设置教学记录人签名和带教老师签名
     *
     * @param saveOrUpdateVo
     * @param meetingDataNew
     */
    private void setJlrAndTeacherSign(MeetingDataNewSaveOrUpdateVo saveOrUpdateVo, MeetingDataNew meetingDataNew) {
        //申请预约的预约人姓名关联到教学培训下教学记录所有表格中的的记录人签名中
        if (StringUtils.isNotBlank(saveOrUpdateVo.getUserName())) {
            PersonVo personVo = personService.selectVoByName(saveOrUpdateVo.getUserName());
            if (Objects.nonNull(personVo) && StringUtils.isNotBlank(personVo.getSignPic())) {
                meetingDataNew.setJlrSign(personVo.getSignPic());
            }
        }
        //带教老师姓名直接关联到表格中的带教老师签名
        String teacher = saveOrUpdateVo.getTeacher();
        if (StringUtils.isNotBlank(teacher)) {
            PersonVo personVo = personService.selectVoByName(teacher);
            if (Objects.nonNull(personVo) && StringUtils.isNotBlank(personVo.getSignPic())) {
                meetingDataNew.setTeacherSign(personVo.getSignPic());
            }
        }
    }

    @Override
    public boolean saveWithoutApply(MeetingDataNewSaveOrUpdateVo saveOrUpdateVo) {
        MeetingDataNew meetingDataNew = new MeetingDataNew();
        BeanUtils.copyProperties(saveOrUpdateVo, meetingDataNew);

        FaceMeetingSyncMeetingRequestDto faceMeetingSyncMeetingRequestDto = new FaceMeetingSyncMeetingRequestDto();
        faceMeetingSyncMeetingRequestDto.setTheme(saveOrUpdateVo.getTitle());
        faceMeetingSyncMeetingRequestDto.setMrname(saveOrUpdateVo.getAddress());
        faceMeetingSyncMeetingRequestDto.setStime(saveOrUpdateVo.getDate() + " " + saveOrUpdateVo.getTime());
        DateTime startTimeDate = DateUtil.parseDateTime(saveOrUpdateVo.getDate() + " " + saveOrUpdateVo.getTime() + ":00");
        //默认一小时后结束
        DateTime endTimeDate = DateUtil.offsetHour(startTimeDate, 1);
        faceMeetingSyncMeetingRequestDto.setEtime(DateUtil.format(endTimeDate, new SimpleDateFormat("yyyy-MM-dd HH:mm")));
        faceMeetingSyncMeetingRequestDto.setUsername(saveOrUpdateVo.getUserName());

        FaceMeetingSyncMeetingResponseDto faceMeetingSyncMeetingResponseDto = FaceMeetingUtil.setMeeting(faceMeetingSyncMeetingRequestDto);
        try {
            if (Objects.nonNull(faceMeetingSyncMeetingResponseDto)) {
                //保存远程会议ID
                meetingDataNew.setRemoteMeetingId(faceMeetingSyncMeetingResponseDto.getReturnData().getMeetingid());
            }
        } catch (Exception v) {
            v.printStackTrace();
        }
        //设置教学记录人签名和带教老师签名
        setJlrAndTeacherSign(saveOrUpdateVo, meetingDataNew);
        return this.insert(meetingDataNew) != 0;
    }

    @Override
    public boolean modify(MeetingDataNewSaveOrUpdateVo saveOrUpdateVo) {
        MeetingDataNew old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        MeetingDataNew meetingDataNew = new MeetingDataNew();
        BeanUtils.copyProperties(saveOrUpdateVo, meetingDataNew);
        return this.update(meetingDataNew);
    }

    @Override
    public MeetingDataNewVo selectOne(MeetingDataNewSearchVo meetingDataNewSearchVo) {
        return mapper.selectOne(meetingDataNewSearchVo);
    }

    @Override
    public Integer count(MeetingDataNewSearchVo meetingDataNewSearchVo) {
        return mapper.count(meetingDataNewSearchVo);
    }

    @Override
    public List<MeetingDataNewVo> selectList(MeetingDataNewSearchVo meetingDataNewSearchVo) {
        List<MeetingDataNewVo> meetingDataNewVos = mapper.selectList(meetingDataNewSearchVo);
        if (CollectionUtil.isEmpty(meetingDataNewVos)) {
            return Collections.emptyList();
        }
        for (MeetingDataNewVo meetingDataNewVo : meetingDataNewVos) {
            //PPT文件地址数组
            List<FileVo> visitFileVos = fileService.selectList(FileSearchVo.builder()
                    .dataId(meetingDataNewVo.getId())
                    .type(FileTypeEnum.TEACH_PPT.getCode().byteValue())
                    .build());
            if (CollectionUtil.isNotEmpty(visitFileVos)) {
                meetingDataNewVo.setPptFilePathList(visitFileVos.stream().map(fileVo -> {
                    FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                    fileSaveOrUpdateVo.setFileName(fileVo.getName());
                    fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                    return fileSaveOrUpdateVo;
                }).collect(Collectors.toList()));
            }
            //图片文件地址数组
            List<FileVo> picFileVos = fileService.selectList(FileSearchVo.builder()
                    .dataId(meetingDataNewVo.getId())
                    .type(FileTypeEnum.TEACH_PIC.getCode().byteValue())
                    .build());
            if (CollectionUtil.isNotEmpty(picFileVos)) {
                meetingDataNewVo.setPicFilePathList(picFileVos.stream().map(fileVo -> {
                    FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                    fileSaveOrUpdateVo.setFileName(fileVo.getName());
                    fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                    return fileSaveOrUpdateVo;
                }).collect(Collectors.toList()));
            }
        }

        return meetingDataNewVos;
    }

    @Override
    public Page<MeetingDataNewVo> selectPage(MeetingDataNewSearchVo meetingDataNewSearchVo) {
        AssertUtil.check(Objects.isNull(meetingDataNewSearchVo.getPageNum()) || Objects.isNull(meetingDataNewSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(meetingDataNewSearchVo);
        //分页
        Page<MeetingDataNewVo> page = new Page<>(true, count, meetingDataNewSearchVo.getPageNum(), meetingDataNewSearchVo.getPageSize());
        meetingDataNewSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<MeetingDataNewVo> responseVos = this.selectList(meetingDataNewSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<MeetingDataNew> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(MeetingDataNewSearchVo meetingDataNewSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(meetingDataNewSearchVo);
    }

    @Override
    public boolean savePPT(Long id, List<FileSaveOrUpdateVo> fileSaveOrUpdateVos) {
        fileService.deleteByCondition(FileSearchVo.builder()
                .dataId(id)
                .type(FileTypeEnum.TEACH_PPT.getCode().byteValue())
                .build());
        fileService.insertBatch(fileSaveOrUpdateVos, FileTypeEnum.TEACH_PPT.getCode().byteValue(), id);
        return true;
    }

    @Override
    public boolean savePic(Long id, List<FileSaveOrUpdateVo> fileSaveOrUpdateVos) {
        fileService.deleteByCondition(FileSearchVo.builder()
                .dataId(id)
                .type(FileTypeEnum.TEACH_PIC.getCode().byteValue())
                .build());
        fileService.insertBatch(fileSaveOrUpdateVos, FileTypeEnum.TEACH_PIC.getCode().byteValue(), id);
        return false;
    }

    @Override
    public List<MeetingDataNewCalendarVo> getMeetingDataNewCalendarVoByMonth(String month) {
        //找出这个月份所有的数据
        List<MeetingDataNewVo> meetingDataNewVos = mapper.selectList(MeetingDataNewSearchVo.builder()
                .month(month)
                .build());
        if (CollectionUtil.isEmpty(meetingDataNewVos)) {
            return Collections.emptyList();
        }
        Map<String, List<MeetingDataNewVo>> map = meetingDataNewVos.stream().collect(Collectors.groupingBy(MeetingDataNewVo::getDate, Collectors.toList()));
        List<MeetingDataNewCalendarVo> result = Lists.newLinkedList();
        map.forEach((k, v) -> {

            List<String> v1 = v.stream().map(s -> {
                //类型
                Byte type = s.getType();
                String typeStr;
                switch (type.intValue()) {
                    case 1:
                        typeStr = "小讲座";
                        break;
                    case 2:
                        typeStr = "教学病历讨论";
                        break;
                    case 3:
                        typeStr = "教学读片";
                        break;
                    default:
                        typeStr = "小讲座";
                        break;
                }
                return String.format("%s %s %s", s.getTime(), typeStr, s.getTitle());
            }).collect(Collectors.toList());

            MeetingDataNewCalendarVo k2 = new MeetingDataNewCalendarVo();
            k2.setDay(k);
            k2.setData(v1);
            result.add(k2);
        });
        return result;
    }

    @Override
    public boolean loginSign(LoginMeetingSignVo loginVo) {
        MeetingDataNew meetingDataNew = this.selectById(loginVo.getMeetingId());
        AssertUtil.notNull(meetingDataNew, "此会议不存在或者已被删除");
        Person personVo = personService.selectByJobNumberAndPassword(loginVo.getJobNumber(), null);
        if (null == personVo) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "工号或密码不正确");
        }
        //给前台传过来的密码加盐，然后加密
        String password = EncryptUtil.password(loginVo.getPassword(), personVo.getSalt());
        if (!password.equals(personVo.getPassword())) {
            throw new BusinessException(ResponseCodeEnum.FAILURE.code, "工号或密码不正确");
        }
        AssertUtil.check(StringUtils.isBlank(personVo.getSignPic()), "此用户还未上传签字图片");
        //人类型
        Byte type = personVo.getType();
        PersonTypeEnum personTypeEnum = PersonTypeEnum.getByCode(type.intValue());
        assert personTypeEnum != null;
        switch (personTypeEnum) {
            case ZZYG:
                //在职人员
                String doctorSign = meetingDataNew.getDoctorSign();
                String doctorIds = meetingDataNew.getDoctorIds();
                String updateDoctorSign;
                String updateDoctorIds;
                if (StringUtils.isBlank(doctorSign)) {
                    //第一个签到，直接修改
                    updateDoctorSign = personVo.getSignPic();
                } else {
                    updateDoctorSign = doctorSign + "," + personVo.getSignPic();
                }
                if (StringUtils.isBlank(doctorIds)) {
                    updateDoctorIds = personVo.getId() + "";
                } else {
                    updateDoctorIds = doctorIds + "," + personVo.getId();
                }
                this.updateByPrimaryKeySelective(MeetingDataNew.builder()
                        .id(meetingDataNew.getId())
                        .doctorSign(updateDoctorSign)
                        .doctorIds(updateDoctorIds)
                        .build());
                break;
            case JXS:
                //进修生
                String jxsSign = meetingDataNew.getJxsSign();
                String jxsIds = meetingDataNew.getJxsIds();
                String updateJxsSign;
                String updateJxsIds;
                if (StringUtils.isBlank(jxsSign)) {
                    //第一个签到，直接修改
                    updateJxsSign = personVo.getSignPic();
                } else {
                    updateJxsSign = jxsSign + "," + personVo.getSignPic();
                }
                if (StringUtils.isBlank(jxsIds)) {
                    //第一个签到，直接修改
                    updateJxsIds = personVo.getId() + "";
                } else {
                    updateJxsIds = jxsIds + "," + personVo.getId();
                }
                this.updateByPrimaryKeySelective(MeetingDataNew.builder()
                        .id(meetingDataNew.getId())
                        .jxsSign(updateJxsSign)
                        .jxsIds(updateJxsIds)
                        .build());
                break;
            case GPS:
            case YJS:
                //规培生或者研究生
                String gpsYjsSign = meetingDataNew.getGpsYjsSign();
                String gpsYjsIds = meetingDataNew.getGpsYjsIds();
                String updateGpsYjsSign;
                String updateGpsYjsIds;
                if (StringUtils.isBlank(gpsYjsSign)) {
                    //第一个签到，直接修改
                    updateGpsYjsSign = personVo.getSignPic();
                } else {
                    updateGpsYjsSign = gpsYjsSign + "," + personVo.getSignPic();
                }
                if (StringUtils.isBlank(gpsYjsIds)) {
                    //第一个签到，直接修改
                    updateGpsYjsIds = personVo.getId() + "";
                } else {
                    updateGpsYjsIds = gpsYjsIds + "," + personVo.getId();
                }
                this.updateByPrimaryKeySelective(MeetingDataNew.builder()
                        .id(meetingDataNew.getId())
                        .gpsYjsSign(updateGpsYjsSign)
                        .gpsYjsIds(updateGpsYjsIds)
                        .build());
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public String createNextCode(Byte type) {
        MeetingNewTypeEnum personTypeEnum = MeetingNewTypeEnum.getByCode(type.intValue());
        assert personTypeEnum != null;
        String maxCode = this.selectMaxCode(type);
        if (StringUtils.isBlank(maxCode)) {

            return String.format("%s-%s-1", personTypeEnum.getNumber(), DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")));
        }
        String[] maxCodeArray = maxCode.split("-");
        Integer i = Integer.valueOf(maxCodeArray[maxCodeArray.length - 1]);
        i++;
        return String.format("%s-%s-%s", personTypeEnum.getNumber(), DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")), i);
    }

    @Override
    public String selectMaxCode(Byte type) {
        return mapper.selectMaxCodeByDay(type, DateUtil.formatDate(new Date()));
    }

}